package com.alstudio.ui.module.main;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.event.ALEventDeliver;
import com.alstudio.module.ALModuleManager;
import com.alstudio.module.voip.ALPostToRtpServerData;
import com.alstudio.module.voip.ALVoipEvent;
import com.alstudio.module.voip.ALVoipEventType;
import com.alstudio.module.voip.ALVoipModuleManager;
import com.alstudio.module.xmpp.protocol.xmpp.ALXmppEventNotifyManager;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppConnectionState;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppData;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.module.xmpp.request.ALUiXmppRequestType;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.ui.base.BaseActivity;
import com.alstudio.utils.android.net.ALConnectionManager;
import com.alstudio.utils.android.net.ALConnectionManager.ALConnectionType;
import com.loovee.imaohu.R;

public class MainActivity2 extends BaseActivity implements OnClickListener,
		com.alstudio.utils.android.net.ALWifiManager.WifiStateChangedCallback {

	private final String TAG = "MainActivity";
	private Button login, call;
	private EditText ip, port, user, pwd, voip_ip, voip_user;
	private TextView state, message;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(this, TAG);
		initData();
		startPush();
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setContentRes(R.layout.main_activity);
		login = (Button) findViewById(R.id.login);
		ip = (EditText) findViewById(R.id.ip);
		port = (EditText) findViewById(R.id.port);
		user = (EditText) findViewById(R.id.user);
		pwd = (EditText) findViewById(R.id.pwd);

		state = (TextView) findViewById(R.id.state);
		message = (TextView) findViewById(R.id.message);
		setViewOnclickListener(login, this);
		setViewOnclickListener(R.id.login_default, this);
		setViewOnclickListener(R.id.logoff, this);
		setViewOnclickListener(R.id.send, this);
		setViewOnclickListener(R.id.test_imageloader, this);
		// init voip
		initVoip();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ALEventDeliver.getDefaultAlEventDeliver().register(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		ALEventDeliver.getDefaultAlEventDeliver().unregister(this);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		setButtonText();
		// 设定本界面需要监听xmpp事件回调
		enableReceiveALXmppEvent();
	}

	private void setButtonText() {

	}

	@Override
	public void onClick(final View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.login:
			doLogin();
			break;
		case R.id.login_default:
			dodefaultLogin();
			break;
		case R.id.logoff:
			doLogOff();
			break;
		case R.id.send:
			doSendMessageToMySelf();
			break;
		case R.id.call:
			doCall();
			break;
		case R.id.test_imageloader:
			// Intent i = new Intent(MainActivity.this,TestImageLoader.class);
			// startActivity(i);

			ALModuleManager
					.getDefaultModuleManager()
					.postEventToModuleManager(
							ALUiXmppRequestCreator
									.creatorALUiXmppEvent(
											ALUiXmppRequestType.XMPP_CANCEL_CALL_REQUEST,
											"xxx"));

			// DistributorManager.getInstance().checkDistributor("V1.0.0");
			// DistributorManager.getInstance().checkDistributor("V1.0.0",
			// "Android", "116.254.203.117", "9225", true);
			// VersionManager.getInstance().checkNewVersion("V1.0.0", "Android",
			// "116.254.203.117", "9225");

			// doSinaLogin();
			// WeiXinShare weixin = new WeiXinShare();
			// weixin.share(MainActivity.this, "xxx",
			// "http://open.weixin.qq.com/static/zh_CN/app/images/logo.zh_CN.png",
			// false, null);

			// SinaShare sina = new SinaShare();
			// sina.share(MainActivity.this, "xxx",
			// "http://open.weixin.qq.com/static/zh_CN/app/images/logo.zh_CN.png",
			// false, null);

			// TencentShare ts = new TencentShare();
			// ts.share(MainActivity.this, "xxxx",
			// ALSdcardManager.getExtStoragePath()+"/alonso.jpg", false, null);
			// ts.shareWithImageUrl(MainActivity.this, "xxxx",
			// "http://e.hiphotos.baidu.com/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=d3bb12b08a82b90129a0cb6112e4c212/8b13632762d0f7038dc8ac4b08fa513d279759ee3d6de512.jpg",
			// false, null);

			// ITencent tencent = new ITencent(MainActivity.this,
			// SnsConfig.TENCENT_APP_ID, SnsConfig.TENCENT_SCOPE);
			// tencent.login(MainActivity.this, SnsConfig.TENCENT_SCOPE, new
			// OnAuthEventListener() {
			//
			// @Override
			// public void onCancel() {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void onAuthSuccess() {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void onAuthFailed(int ret, String msg) {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void doComplete(JSONObject response) {
			// // TODO Auto-generated method stub
			// }
			// });

			break;
		}
	}

	@Override
	public void onWifiStateChangedCallback(boolean state) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDataConnectionEstablished(ALConnectionType type) {
		// TODO Auto-generated method stub
		super.onDataConnectionEstablished(type);
		if (type == ALConnectionType.TYPE_WIFI) {
		}
	}

	@Override
	public void onDataConnectionLost() {
		// TODO Auto-generated method stub
		super.onDataConnectionLost();
	}

	private void doLogin() {
		String ipAddr = ip.getText().toString().trim();
		String portAddr = port.getText().toString().trim();
		String username = user.getText().toString().trim();
		String passwd = pwd.getText().toString().trim();
		if (TextUtils.isEmpty(ipAddr)) {
			Toast.makeText(this, "你没填ip地址", Toast.LENGTH_SHORT).show();
			return;
		}

		if (TextUtils.isEmpty(portAddr)) {
			Toast.makeText(this, "你没填端口", Toast.LENGTH_SHORT).show();
			return;
		}

		if (TextUtils.isEmpty(username)) {
			Toast.makeText(this, "你没填账号", Toast.LENGTH_SHORT).show();
			return;
		}

		if (TextUtils.isEmpty(passwd)) {
			Toast.makeText(this, "你没填密码", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!ALConnectionManager.isNetWorkConnected()) {
			Toast.makeText(this, "你没可用网络", Toast.LENGTH_SHORT).show();
			return;
		}
		ALXmppData data = new ALXmppData(ipAddr, portAddr, "mk", 50);
		data.setUsername(username);
		data.setPassword(passwd);

		ALLocalEnv.adapter.xmppLogin(data);
	}

	private void dodefaultLogin() {
		if (!ALConnectionManager.isNetWorkConnected()) {
			Toast.makeText(this, "你没可用网络", Toast.LENGTH_SHORT).show();
			return;
		}
//		ALXmppData data = new ALXmppData("116.254.203.117", "5755", "mk", 50);
//		data.setUsername("235517");
//		data.setPassword("123456");
//
//		ALLocalEnv.adapter.xmppLogin(data);
		
//		ALLocalEnv.getLocalEnv().getMyAccount().setUserName("fcyxx4238@126.com");
		ALLocalEnv.getLocalEnv().getMyAccount().setUserName("235517");
		ALLocalEnv.getLocalEnv().getMyAccount().setPassWord("123456");
		
		ALModuleManager
		.getDefaultModuleManager()
		.postEventToModuleManager(
				ALUiXmppRequestCreator
						.creatorALUiXmppEvent(
								ALUiXmppRequestType.XMPP_LOGIN_REQUEST,
								null));
		
	}

	private void doLogOff() {
		if (!ALLocalEnv.adapter.isLogined()) {
			Toast.makeText(this, "你都没登陆", Toast.LENGTH_SHORT).show();
			return;
		}
		ALLocalEnv.adapter.xmppLogOff();
	}

	private void doSendMessageToMySelf() {
		if (!ALLocalEnv.adapter.isLogined()) {
			Toast.makeText(this, "你都没登陆", Toast.LENGTH_SHORT).show();
			return;
		}
		ALMessage m = new ALMessage("200278@mk", "235517@mk");
		m.setType(ALMessage.TEXT_MSG);
		m.setBody("我只是给自己发条测试消息测试消息");
		m.getMsgId();
		m.setFromNick("alonso");
		// 把收到的消息发回去
		ALLocalEnv.adapter.xmppSendMessage(m);
	}

	@Override
	public void handleConnectStateChangedEvent(ALXmppConnectionState newState,
			ALXmppConnectionState lastState) {
		// TODO Auto-generated method stub
		super.handleConnectStateChangedEvent(newState, lastState);
		String nowState = ALXmppEventNotifyManager
				.connectionState2String(newState);
		// Toast.makeText(MainActivity.this, nowState,
		// Toast.LENGTH_SHORT).show();
		state.setText(nowState);
	}

	@Override
	public void handleOnConflictEvent() {
		// TODO Auto-generated method stub
		super.handleOnConflictEvent();
		// 被踢下线
		state.setText("你被踢下线了");

	}

	@Override
	public void handleConnectionLostEvent(String errorMessage) {
		// TODO Auto-generated method stub
		super.handleConnectionLostEvent(errorMessage);
		// 连接断开
		state.setText("连接断开了：" + errorMessage);
	}

	@Override
	public void handleAuthFailedEvent(String errorMessage) {
		// TODO Auto-generated method stub
		super.handleAuthFailedEvent(errorMessage);
		// 账号验证失败
		state.setText("账号验证失败");

	}

	@Override
	public void handleLogoutEvent() {
		// TODO Auto-generated method stub
		super.handleLogoutEvent();
		// 注销成功
		state.setText("已经离线");
	}

	@Override
	public void handleLoginedEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleLoginedEvent(data);
		state.setText("登陆成功！当前账号为: " + data.getJid() + " 密码为  " + data.getPwd());
		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				ALUiXmppRequestCreator.creatorALUiXmppEvent(
						ALUiXmppRequestType.XMPP_VOIP_UPLOAD_LOCAL_NETWORK_STAT, ALConnectionManager
						.getConnectionTypeString()));
	}

	@Override
	public void handleOnNewMessageArrivedEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleOnNewMessageArrivedEvent(msg);
		handleNewMessage(msg);
	}

	@Override
	public void handleOnMessageReceiptEvent() {
		// TODO Auto-generated method stub
		super.handleOnMessageReceiptEvent();
	}

	@Override
	public void handleNewIncommingCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewIncommingCallEvent(msg);
		String txt = "";
		txt = msg.getFromNick() + "来电";
		message.setText(txt);

	}

	@Override
	public void handleUserAcceptCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserAcceptCallEvent(msg);
		String txt = "";
		txt = msg.getFromNick() + "接通啦";
		message.setText(txt);
	}

	@Override
	public void handleUserHandupEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserHandupEvent(msg);
		String txt = "";
		txt = msg.getFromNick() + "挂断啦";
		message.setText(txt);
	}

	@Override
	public void handleUserRejectCallEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleUserRejectCallEvent(msg);
		String txt = "";
		txt = msg.getFromNick() + "拒绝来电";
		message.setText(txt);
	}

	/******************************* 功能处理 *************************************/
	private void handleNewMessage(ALMessage msg) {
		String txt = "";
		switch (msg.getType()) {
		case ALMessage.NEW_INCOMMING_CALL:
			txt = msg.getFromNick() + "来电";
			break;
		case ALMessage.USER_ACCEPT_CALL:
			txt = msg.getFromNick() + "接通啦";
			break;
		case ALMessage.USER_HANDUP_CALL:
			txt = msg.getFromNick() + "挂断啦";
			break;
		case ALMessage.USER_REJECT_CALL:
			txt = msg.getFromNick() + "拒绝来电";
			break;
		default:
			txt = ("收到来自 " + msg.getFromNick() + " 的消息 " + msg.getBody());

			break;
		}
		message.setText(txt);

	}

	/******************************* 功能处理 end *************************************/

	/***************************************** voip **********************************************/
	private void initVoip() {
		voip_ip = (EditText) findViewById(R.id.voip_ip);
		voip_user = (EditText) findViewById(R.id.voip_user);
		call = (Button) findViewById(R.id.call);
		setViewOnclickListener(call, this);
	}

	private void doCall() {
		// AlertDialogCreator dialog =
		// AlertDialogCreator.createOneButtonNormalDialog(this, false);
		// dialog.setMessage("xx");
		// dialog.showDialog();
		udpTest();
	}

	/*****************************************
	 * voip
	 * 
	 * @throws Exception
	 **********************************************/

	private void udpTest() {
		String user = ALLocalEnv.adapter.getXmppData().getUsername();
		ALPostToRtpServerData data = ALVoipModuleManager
				.getPostToRtpServerData(user, getIp(), 4000,
						ALConnectionManager.getConnectionTypeString(),
						ALVoipModuleManager.DEFAULT_RTP_SERVER_IP,
						ALVoipModuleManager.DEFAULT_RTP_SERVER_PORT);
		// ALVoipModuleManager.getDefaultALVoipModuleManager()
		// .postUdpDataToServer(data);

		ALVoipEvent event = new ALVoipEvent();
		event.setData(data);
		event.setEventType(ALVoipEventType.ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER);
		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);
	}


	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}
	
	/* (non-Javadoc)
	 * @see com.alstudio.ui.base.BaseActivity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		backToSystemHome();
	}

	private void startPush() {
//		ALPushManager.getDefaultPushManager().registerModule(
//				ALLocalEnv.getLocalEnv().getContext());
	}

	public void onALEvent(ALVoipEvent event) {
		if (!isActivityOn()) {
			return;
		}
		switch (event.getEventType()) {
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_SUCCESS:
			String user = voip_user.getText().toString();
			// ALLocalData data = new
			// ALLocalData(ALXmppEventType.XMPP_MAKE_CALL_REQUEST);
			// data.setJid(user + "@mk");
			// ALLocalEnv.adapter.xmppMakeVoipCall(user + "@mk");

			ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
					ALUiXmppRequestCreator.creatorALUiXmppEvent(
							ALUiXmppRequestType.XMPP_MAKE_CALL_REQUEST, user
									+ "@mk"));
			break;
		case ALVOIP_EVENT_POST_DATA_TO_RTP_SERVER_FAIL:
			break;
		case ALVOIP_EVENT_START_STREAM_TO_REMOTE_USER:
			break;
		case ALVOIP_EVENT_STOP_STREAM_TO_REMOTE_USER:
			break;
		default:
			break;
		}
	}

}
